package com.itheima.stock.service.Impl;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.RedisConstants;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/11/7 10:38
 */
@Service
public class UserServiceImpl implements UserService {
    private final Cache cache;
    private final IdWorkers idWorkers;

    public UserServiceImpl(Cache cache, IdWorkers idWorkers) {
        this.cache = cache;
        this.idWorkers = idWorkers;
    }


    @Override
    public CaptchaVO generateCaptcha() {

        // 1. 使用工具类生成一个随机的4位验证码
        String captcha = RandomStringUtils.randomNumeric(4);
        // 2. 将验证码存入缓存
        // 生成key的后缀
        String keySuffix = idWorkers.nextStrId();
        // 生成key
        String redisKey = RedisKeyUtil.generateKey(RedisConstants.CAPTCHA_PREFIX, keySuffix);
        // 存入缓存，并且设置过期时间
        cache.set(redisKey, captcha, RedisConstants.CAPTCHA_EXPIRE);
        // 3. 数据组装返回
        return CaptchaVO.builder()
                        .code(captcha)
                        .rkey(redisKey)
                        .build();
    }
}
